package top.mollysu.sell.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Author kosmosr
 * @Date 2018/3/24
 * 密码处理工具
 */
public class PasswordUtils {

    /**
     * 加密密码
     * @param password 密码
     * @return
     */
    public static String encode(String password) {
        MessageDigest messageDisgest = null;
        try {
            messageDisgest = MessageDigest.getInstance("SHA-512");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        messageDisgest.update(password.getBytes());

        byte[] digest = messageDisgest.digest();
        for (int i = 0; i < 512; i++) {
            digest = messageDisgest.digest(digest);
        }

        try {
            return new String(Base64.encodeBase64(digest), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static boolean equalPwd(String inputPassword, String password) {
        if (StringUtils.isBlank(inputPassword)) {
            return false;
        }
        System.out.println(encode(inputPassword));
        if (encode(inputPassword).equals(password)) {
            return true;
        }
        return false;
       // return encode(inputPassword).equals(password);
    }
}
